<?php
// 应用公共文件

	//***************************【Thinkphp辅助函数】***********************************
	function F($name,$val='',$option=0){
		if($val===''){
			return cache($name);
		}else if(is_null($val)){
			cache($name,null);
		}else{
			cache($name,$val,$option);	
		}
	}
	
	// 生成URL
	/*
	 *	block  是否跨模块生成链接
	 */
	function U($action,$get=[],$domain=false,$block='',$suffix=true){
		$route_domains=env('route.domains',0);
		//没开启多域名多模块
		if(!$route_domains && $block!='') $action.='/'.$block.'/'.$action;

		$url=url($action,$get,$suffix,$domain);

		if($route_domains==1){					//是否多域名多模块
			$url_arr=parse_url($url);
			if(isset($url_arr['host'])){
				if($block!=''){				//跳转指定模块
					$host=array_search($block,config('app.domain_bind'));
				}else{
					$host=$_SERVER['HTTP_HOST'];
				}
				$url=str_replace($url_arr['host'],$host,$url);		
			}
		}
		if(!is_string($url)) $url=(string)$url;
		return $url;
	}
	
	//I函数的获取请求变量
	function I($name,$default='',$filter=''){
		return input($name,$default,$filter);
	}
	
	//跳转函数
	function jump($action){
		$domains=env('route.domains',0);
		if($domains==1){
			$action='/'.$action;
		}else{
			$app_name=app('http')->getName();
			$action='/'.$app_name.'/'.$action;
		}
		return redirect(U($action));
	}

    //清除缓存
    function rm()
    {
        delete_dir(root_path().'runtime');
    }

    //是否URL
    function is_url($url)
    {
        if(preg_match("/^http(s)?:\\/\\/.+/",$url)) return $url;
    }

    /**
     *  随机数
     *
     * @param string $length 长度
     * @param string $type   类型
     * @return void
     */
    function rand_string($length = '32',$type=4): string
    {
        $rand='';
        switch ($type) {
            case '1':
                $randstr= '0123456789';
                break;
            case '2':
                $randstr= 'abcdefghijklmnopqrstuvwxyz';
                break;
            case '3':
                $randstr= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
            default:
                $randstr= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
        }
        $max = strlen($randstr)-1;
        mt_srand((double)microtime()*1000000);
        for($i=0;$i<$length;$i++) {
            $rand.=$randstr[mt_rand(0,$max)];
        }
        return $rand;
    }


    //密码截取
    function set_password($password): string
    {
      return substr(md5($password), 3, -3);
    }

	/**
	 * 数据签名认证
	 */
	function data_sign($data = [])
	{
		if (!is_array($data)) {
			$data = (array)$data;
		}
		ksort($data);
		$code = http_build_query($data);
		$sign = sha1($code);
		return $sign;
	}

	/**
	 * 获取或修改扩充配置文件
	 */
    function config_cache_file($name='web',$data = [],$type='extra')
    {
		if(count($data)>0){				//设置
			set_config_file_data($name,$data,$type);
		}else{
			try{
				//获取单个配置文件
				if(!is_array($name)){
					$name=explode('.',$name);
					$data=get_config_file_data($name[0],$type);
					if(count($name)>1){
						unset($name[0]);
						return spot_key($data,$name);
					}else{
						return $data;
					}
				}else{		//获取多个配置文件
					return get_config_file_data($name,$type);
				}
			}catch(\Exception $e){
				return '';
			}
		}
    }

	/**
	 * 获取配置文件数据途径
	 */
	function get_config_file_data($name,$type){
		if($type=='sql'){		//数据库获取
			
		}else if($type=='extra'){
			$path=config_path().$type.'/';
			$data=[];
			if(is_array($name)){
				foreach($name as $key){
					$data[$key]=require $path.$key.'.php';
				}
				return $data;
			}else{
				return require $path.$name.'.php';
			}
		}
	}
	
	/**
	 * 设置配置文件数据途径
	 */
	function set_config_file_data($name,$data=[],$type){
		if($type=='sql'){		//数据库获取
			
		}else if($type=='extra'){
			$title=config_cache_file('config_title.'.$name);
			$str = "<?php\r\n/**\r\n * ".$title."\r\n */\r\nreturn ";
			$str .= array_text($data);
			$str .= "?>";
			@file_put_contents(config_path().$type.'/'.$name.'.php', $str);
		}
	}
	
	// 数据格式化
	function array_text($data,$name=''){
		if($name!=''){
			$str="\$".$name." = ";
		}else{
			$str='';
		}
		$str .= "[\r\n";
		foreach ($data as $key => $value) {
		    if(is_array($value)){
				$str .= get_arr_tree($key,$value);
		    }else{
		        $str .= "\t'$key' => '$value',";
		        $str .= "\r\n";
		    }
		}
		$str .= '];';
		$str .= "\r\n";
		return $str;
	}

    /**
     * 递归配置数组
     */
    function get_arr_tree($key,$data,$level="\t")
    {
        $i = "$level'$key' => [\r\n";
        foreach ($data as $k => $v) {
            if(is_array($v)){
                $i .= get_arr_tree($k,$v,$level."\t");
            }else{
                $i .= "$level\t'$k' => '$v',";
                $i .= "\r\n";      
            }
        }
        return  $i."$level".'],'."\r\n";
    }

    /**
     *
     * @param string $string 需要加密的字符串
     * @param string $key 密钥
     * @return string
     */
    function aes_encrypt($string, $key="ONSPEED"): string
    {
        $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return strtolower(bin2hex($data));
    }


    /**
     * @param string $string 需要解密的字符串
     * @param string $key 密钥
     * @return string
     */
    function aes_decrypt($string, $key="ONSPEED"): string
    {
        try {
            return openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        }catch (\Exception $e){
            return false;
        }
    }


    /**
     * 获取指定表指定行指定字段
     * @param  string       $tn      完整表名
     * @param  string|array $where   参数数组或者id值
     * @param  string       $field   字段名,默认'name'
     * @param  string       $default 获取失败的默认值,默认''
     * @param  array        $order   排序数组
     * @return string                获取到的内容
     */
    function get_field($tn, $where, $field = 'name', $default = '', $order = ['id' => 'desc'])
    {
        if (!is_array($where)) {
            $where = ['id' => $where];
        }
        $row = \think\facade\Db::name($tn)->field([$field])->where($where)->order($order)->find();
        return $row === null ? $default : $row[$field];
    }


    /**
     * 遍历删除文件夹所有内容
     * @param  string $dir 要删除的文件夹
     */
    function delete_dir($dir)
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != '.' && $file != '..') {
                $filepath = $dir . '/' . $file;
                if (is_dir($filepath)) {
                    delete_dir($filepath);
                } else {
                    @unlink($filepath);
                }
            }
        }
        closedir($dh);
        @rmdir($dir);
    }

    /**
     * 递归无限级分类权限
     * @param array $data
     * @param int $pid
     * @param string $field1 父级字段
     * @param string $field2 子级关联的父级字段
     * @param string $field3 子级键值
     * @return mixed
     */
    function get_tree($data, $pid = 0, $field1 = 'id', $field2 = 'pid', $field3 = 'children')
    {
        $arr = [];
        foreach ($data as $k => $v) {
            if ($v[$field2] == $pid) {
                $v[$field3] = get_tree($data, $v[$field1]);
                $arr[] = $v;
            }
        }
        return $arr;
    }


    /**
     * 驼峰转下划线
     * @param  string $str 需要转换的字符串
     * @return string      转换完毕的字符串
     */
    function hump_underline($str)
    {
        return strtolower(trim(preg_replace('/[A-Z]/', '_\\0', $str), '_'));
    }


    /**
     * 下划线转驼峰
     * @param  string $str 需要转换的字符串
     * @return string      转换完毕的字符串
     */
    function underline_hump($str)
    {
        return ucfirst(
            preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $str)
        );
    }

    /**
     * @记录日志
     * @param [type] $param
     * @param string $file
     *
     * @return void
     */
     function record_log($param,$file=''){
        $path = root_path().'log/'.$file."/";
        if (!is_dir($path)) @mkdir($path,0777,true);
        if (is_array($param)){
            $param = json_encode($param,JSON_FORCE_OBJECT|JSON_UNESCAPED_UNICODE);
        }
        @file_put_contents(
            $path.date("Y_m_d",time()).".txt",
            "执行日期："."\r\n".date('Y-m-d H:i:s', time()) . ' ' . "\n" . $param . "\r\n",
            FILE_APPEND
        );
	}
	
	$req_arr=[
		'arrays.php',					//加载数组函数
		'file.php',						//加载文件函数	
		'upload.php',					//加载上传函数	
		'encrypt.php',					//加载加密函数	
		'template.php',					//加载模板函数
		//'weixin.php',					//加载微信函数
		'layui.php',					//加载layui通用模块
	];
	foreach($req_arr as $v){
		require_once dirname(__DIR__).'/common/'.$v;
	}


	/*
	 * 是否移动端访问访问
	 */
	function isMobile(){
		$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $is_pc = (strpos($agent, 'windows nt')) ? true : false;
        //$is_mac = (strpos($agent, 'mac os')) ? true : false;
        $is_iphone = (strpos($agent, 'iphone')) ? true : false;
        $is_android = (strpos($agent, 'android')) ? true : false;
        $is_ipad = (strpos($agent, 'ipad')) ? true : false;
		
        if($is_pc){
           return  false;
        }
        
        /*if($is_mac){
           return  true;
        }*/
        
        if($is_iphone){
           return  true;
        }
        
        if($is_android){
           return  true;
        }
        
        if($is_ipad){	
           return  true;
        }
	}
	
	//curl方法Post提交
	function curlPost($url,$data,$type=1){
		$ch = curl_init();
		$header = ['Host'=>"Accept-Charset: utf-8"];
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		//调试自定义菜单
		switch($type){
			case 1:						//返回原数据
				return $tmpInfo;
				break;
			case 2:						//返回布尔值
				if (curl_errno($ch)) {
					return false;
				}else{
					return true;
				}
				break;
			case 3:						//返回JSON格式化后的数据
				return json_decode($tmpInfo);
				break;
			case 4:
				return json_decode($tmpInfo,true);		//返回JSON数组
			default:
				break;
		}
	}
	
	//curl方法Get提交
	function curlGet($url,$data,$type=1){
		$ch = curl_init();
		$header = ['Host'=>"Accept-Charset: utf-8"];
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		//调试自定义菜单
		switch($type){
			case 1:						//返回原数据
				return $tmpInfo;
				break;
			case 2:						//返回布尔值
				if (curl_errno($ch)) {
					return false;
				}else{
					return true;
				}
				break;
			case 3:						//返回JSON格式化后的数据
				return json_decode($tmpInfo);
				break;
			case 4:
				return json_decode($tmpInfo,true);		//返回JSON数组
			default:
				break;
		}
		return $temp;
	}